package com.oauth2.provider.bootstrap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import com.oauth2.provider.config.RestServletContextConfig;
import com.oauth2.provider.config.RootContextConfig;
import com.oauth2.provider.config.WebMvcConfig;

@Order(2)
public class Bootstrap implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext container) throws ServletException {

		// 设置静态资源位置
		container.getServletRegistration("default").addMapping("/resource/*");
		//
		AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
		rootContext.register(RootContextConfig.class);
		container.addListener(new ContextLoaderListener(rootContext));

		// 添加Session监听器
		// container.addListener(LWLSessionListener.class);

		/************* web servlet 上下文配置 *****************/
		AnnotationConfigWebApplicationContext servletWebContext = new AnnotationConfigWebApplicationContext();
		servletWebContext.register(WebMvcConfig.class);
		ServletRegistration.Dynamic dispatcher = container.addServlet("springWebDispatcher",
				new DispatcherServlet(servletWebContext));
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/");

		/************* Rest webservice servlet 上下文配置 *****************/
		AnnotationConfigWebApplicationContext restContext = new AnnotationConfigWebApplicationContext();
		restContext.register(RestServletContextConfig.class);
		DispatcherServlet restDispatcherServlet = new DispatcherServlet(restContext);
		restDispatcherServlet.setDispatchOptionsRequest(true);
		ServletRegistration.Dynamic restDispatcher = container.addServlet("springRestDispatcher",
				restDispatcherServlet);
		restDispatcher.setLoadOnStartup(2);
		restDispatcher.addMapping("/rest/*");

	}

}
